/**
 * @Created Oct 1, 2010 3:25:18 PM
 * @author cry30
 */
package com.philip.tool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

/**
 * DBLauncher class with shutdown hook to properly close DB instance. Doing so will prevent loss of data on
 * HSQLDB.
 */
public abstract class HsqldbLauncher { // NOPMD by r39 on 3/30/11 4:38 PM

    /**
     * @param args command line arguments. No argument is expected for now.
     */
    public static void main(final String[] args) {
        final String[] param = {
                "-database.0",
                "file:journaldb",
                "-dbname.0",
                "journaldb" };
        new Thread() { // NOPMD by r39 on 3/30/11 4:38 PM
            @Override
            public void run() {
                org.hsqldb.Server.main(param);
            }
        }.start();
        final Thread shutdown = new Thread(new Runnable() { // NOPMD by r39 on 3/30/11 4:38 PM
                    public void run() {
                        final ResourceBundle resBundle = ResourceBundle.getBundle("db");
                        Connection con = null;
                        Statement stmt = null;
                        try {
                            // Connect to the database and issue SHUTDOWN
                            Class.forName(resBundle.getString("db.driver"));

                            con = DriverManager.getConnection(resBundle.getString("db.url"),
                                    resBundle.getString("db.user"), resBundle.getString("db.pwd"));
                            stmt = con.createStatement();
                            stmt.executeUpdate("SHUTDOWN SCRIPT;");
                            System.out.println("Shutdown script executed successfully."); // NOPMD by r39
                        } catch (final Exception ex) {
                            ex.printStackTrace(); // NOPMD by r39 on 3/30/11 4:38 PM
                        } finally {
                            try {
                                stmt.close();
                                con.close();
                            } catch (final SQLException e) {
                                e.printStackTrace(); // NOPMD by r39 on 3/30/11 4:38 PM
                            }
                        }
                    }
                });
        Runtime.getRuntime().addShutdownHook(shutdown);
    }
}
